<template>
  <div class="box">
    <div class="bg"></div>
    <div class="top-class" id="top">
      <van-nav-bar id="van-bar" title :left-arrow="true" @click-left="onClickLeft">
        <template #left>
          <van-icon name="arrow-left" />
        </template>
        <template #title>
          <div class="title-class">
            <span v-if="infoObj">{{
              infoObj.userInfo[infoObj.key].nickname
            }}</span>
          </div>
        </template>
      </van-nav-bar>
      <div class="jg-class">严禁发布任何形式违规的文字或者图片</div>
      <!-- <div class="user-info-class">
        <div>
          <img src="@/assets/detail/bg.png" />
        </div>
        <div>
          <div>
            <div>第一次看海</div>
            <div class="sex" v-if="userinfo.sex == 2" @click="toeditProfile">
              <img src="../../assets/myicon/nv.png" alt="" srcset="" /><span class="age">{{ userinfo.age }}</span>
            </div>
            <div class="sex" v-if="userinfo.sex == 1" style="background: #cde1fd;" @click="toeditProfile">
              <img src="../../assets/myicon/nan.png" width="12px" alt="" srcset="" /><span class="age"
                style="color:  #3662EC;">{{ userinfo.age }}</span>
            </div>
            <div class="vip" v-if="userinfo.is_svip != 0">VIP</div>
          </div>
          <div>
            <span></span>
            <span>|</span>
            <span></span>
            <span>|</span>
            <span></span>
            <span>|</span>
            <span></span>
          </div>
        </div>
      </div> -->
    </div>
    <van-list direction="up" v-model="loading" :finished="finished" finished-text="— THE END —" @load="getData"
      class="glance" :style="{ height: windowHeight - navbarHeight - dibusrkHeight + 'px' }">
      <div class="rimsg-class lemsg-class" v-for="(item, index) in messages.messages" :key="index">
        <div class="msg-zlist-class" v-if="id != item.from">
          <div>
            <img :src="item.userInfo[item.from].avatarurl" @click="touser(item.from)" />
          </div>
          <div v-if="item.type == 'txt'">
            {{ item.msg }}
          </div>
          <div v-else>
            <van-image width="100" height="100" :src="item.url" />
            <!-- <img style="width: 100px;height: 100px;" :src="item.url" /> -->
          </div>
        </div>

        <div v-else class="msg-rlist-class">
          <div v-if="item.type == 'txt'">
            {{ item.msg }}
          </div>
          <div v-else>
            <van-image width="100" height="100" :src="item.url" />
          </div>
          <div>
            <img :src="item.userInfo[item.from].avatarurl" @click="touser(item.from)" />
          </div>
        </div>
      </div>
    </van-list>
    <div id="dibusrk" :class="istrue ? 'dibusrk-class' : 'dibusrk-class center-class'">
      <div>
        <!-- <input type="file" ref="img" accept="image/jpeg,image/png" @change="getFile($event)"/>/ -->
        <van-uploader :before-read="getFile" :max-size="10000 * 1024">
          <img src="@/assets/chat/btn-image.png" />
        </van-uploader>
      </div>
      <div>
        <img src="@/assets/chat/btn-location.png" />
      </div>
      <div>
        <van-field @input="input" id="fieldgd" rows="1" autosize type="textarea" v-model="msg" placeholder="发送消息..." />
      </div>
      <div>
        <van-button color="linear-gradient(to right, #ff6034, #ee0a24)" @click="sendTextMessage">
          <span>确定</span>
        </van-button>
      </div>
    </div>
  </div>
</template>

<script>
import WebIM from 'easemob-websdk'
import { getUserInfo } from '@/api/index'
import createMsgBody from '@/utils/createMessage'
import { location } from '@/utils/getLocation'
import { sy_convertCityNameToCityCode } from '@/utils/location_convert'
import {
  formatTime
} from '@/utils/fun'
//导入vux
import { mapGetters, mapMutations } from 'vuex'

export default {
  data() {
    return {
      loading: false,
      finished: true,
      msg: '',
      id: '', //消息发送者的id
      toId: '', //消息接收者的id
      istrue: true,
      isstrue: true,
      windowHeight: '',
      navbarHeight: '',
      dibusrkHeight: '',
    }
  },
  computed: {
    ...mapGetters('list', ['infoObj', 'messages', 'options']),
  },
  mounted() {
    this.windowHeight = document.documentElement.clientHeight
    this.navbarHeight = document.getElementById('top').clientHeight
    this.dibusrkHeight = document.getElementById('dibusrk').clientHeight
    this.$nextTick(() => {
      // this.$store.dispatch('list/login').then(res => {

      // })
      // this.issfd = true;
      this.getData()
      // this.onRefresh()
      this.id = this.$store.state.userInfo.uid
      this.toId = Object.keys(this.infoObj.userInfo)[0]

    })
  },
  methods: {
    ...mapMutations('list', ['SET_INFOOBJ', 'SET_options', 'SET_messages', 'SET_sessionlist']),
    //点击头像调整用户详情
    touser(id) {
      if (this.$store.state.is_merchant == 1) {
        this.$router.push({
          path: '/detail',
          query: {
            id: id,
          },
        })
      } else {
        this.$router.push({
          path: '/userDetail',
          query: {
            id: id,
          },
        })
      }
    },
    //内容超出时滚动条默认停留在底部,你需要的时候去调用这个方法即可，要注意异步问题，能否获取到dom元素。
    scrollToBottom() {
      var container = document.getElementsByClassName('van-list')[0];
      container.scrollTop = container.scrollHeight;
    },
    onRefresh() {
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true

      // let options = this.options;
      // options.cursor = -1;
      // this.$store.commit('list/SET_options', options)

      // this.$store.commit('list/SET_messages', {
      //   messages:[]
      // })

      // this.getData()
    },
    async getData() {
      // if (this.issfd) {
      console.log(111111111)
      // if (this.messages) {
      //   if (this.messages.isLast) {
      //     this.finished = true
      //   }
      // }

      this.loading = true
      await this.$store.dispatch('list/getUserChattingRecord').then(res => {
        // let options = this.options;
        if (res) {
          // 清空列表数据
          this.finished = false
          // options.cursor++;
          // this.$store.commit('list/SET_options', options)
          this.scrollToBottom()
          // if (this.isstrue) {
          //   this.scrollToBottom()
          //   this.isstrue = false;
          // }
        } else {
          this.scrollToBottom()
          // 清空列表数据
          this.finished = true
        }
        this.loading = false
      })

      // }

    },
    onClickLeft() {
      this.$router.back()
    },
    input() {
      let gd = document.getElementById('fieldgd').clientHeight
      console.log(gd)
      if (gd > 35) {
        this.istrue = false
      } else {
        this.istrue = true
      }
    },
    // 发送文本消息。
    sendTextMessage() {
      if (this.msg) {

        let option = {
          // 消息类型。
          type: "txt",
          // 消息内容。
          msg: this.msg,
          // 消息接收方：单聊为对方用户 ID，群聊和聊天室分别为群组 ID 和聊天室 ID。
          to: this.toId,
          // 会话类型：单聊、群聊和聊天室分别为 `singleChat`、`groupChat` 和 `chatRoom`，默认为单聊。
          chatType: "singleChat",
        };
        // 创建文本消息。
        let msg = WebIM.message.create(option);
        // 调用 `send` 方法发送该文本消息。
        WebIM.conn.send(msg).then(async (res) => {
          console.log(res, option, msg)

          let messages = this.messages;

          let msgBody = createMsgBody.createMsgBody(msg)

          msgBody.from = this.id;
          msgBody.time = formatTime(msgBody.time)
          msgBody.userInfo = messages.messages[0].userInfo

          messages.messages.push(msgBody)
          messages.cursor = res.serverMsgId;

          this.SET_messages(messages)
          // let options = this.options;
          // options.cursor = res.serverMsgId;
          // this.SET_options({ ...options })

          this.msg = ''
          // this.isstrue = true
          this.$nextTick(() => {
            this.scrollToBottom()
          })

          // await this.getData()
        }).catch((e) => {
          console.log(e);
          this.$toast('信息发送失败!')
        });
      }
    },
    //发送图片
    getFile(files) {
      console.log(files);
      this.isShow = false;
      if (files.type !== 'image/jpeg' && files.type !== 'image/png' && files.type !== 'image/gif') {
        this.$toast('请上传 jpg、png 格式图片');
        return false;
      }

      // 假设您已经获取到上传的文件对象和目标用户的 ID
      var file = files; // 获取上传的文件对象
      var targetUserId = this.toId; // 指定要发送给的用户 ID

      var reader = new FileReader();
      reader.onload = (e) => {
        var fileData = e.target.result; // 获取文件的二进制数据

        // 创建消息对象
        var msg = new WebIM.message("img");

        // 设置消息内容
        var id = WebIM.conn.getUniqueId(); // 生成唯一的消息 ID
        var fileName = file.name; // 获取文件名
        var fileLength = file.size; // 获取文件大小
        var fileUrl = e.target.result; // 获取文件的 URL
        var filetype = { type: file.type, size: file.size }; // 获取文件类型和大小信息

        var body = {
          id: id,
          to: targetUserId,
          type: "img",
          file: { data: fileData, url: fileUrl },
          filename: fileName,
          file_length: fileLength,
          filetype: filetype,
        };

        msg.set(body);
        // 发送消息
        WebIM.conn.send(msg.body).then(res => {
          let msgBody = createMsgBody.createMsgBody(msg.body)

          let messages = this.messages;

          msgBody.from = this.id;
          msgBody.time = formatTime(msgBody.time)
          msgBody.userInfo = messages.messages[0].userInfo

          messages.messages.push(msgBody)
          messages.cursor = res.serverMsgId;

          this.SET_messages(messages)

          // this.msg = ''
          // this.isstrue = true
          this.$nextTick(() => {
            this.scrollToBottom()
          })
          
          console.log(msgBody);
        });
      };

      reader.readAsDataURL(file); // 以 Base64 格式读取文件
    },
  },
}
</script>

<style scoped lang="scss">
::v-deep .van-list {
  overflow-y: auto !important;
}

.bg {
  width: 100%;
  height: 88px;
  position: absolute;
  top: 0;
  background: linear-gradient(180deg, #cde1fd 0%, rgba(255, 255, 255, 0) 100%);
}

.title-class {
  display: flex;
  align-items: center;

  &>span {
    font-size: 16px;
    font-family: PingFangSC, PingFang SC;
    font-weight: 500;
    color: #1a1a1a;
  }

  &>span:nth-child(2) {
    margin: 0px 10px;
  }
}

::v-deep .van-icon-arrow-left {
  color: #1a1a1a !important;
  font-size: 20px !important;
}

.top-class {
  .jg-class {
    height: 20px;
    background: #fcdbdb;
    font-size: 12px;
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    color: #3d3d3d;
    line-height: 20px;
    text-align: center;
  }

  .user-info-class {
    display: flex;
    align-items: center;

    &>div:nth-child(1) {
      &>img {
        width: 40px;
        height: 40px;
        border-radius: 50%;
      }
    }

    &>div:nth-child(2) {
      display: flex;
      flex-direction: column;

      &>div:nth-child(1) {
        display: flex;
        align-items: center;

        .sex {
          background-color: #fcdbdb;
          border-radius: 8px;
          height: 16px;
          width: 38px;
          text-align: center;
          margin-right: 7px;
          line-height: 16px;
          color: #fa5151;

          img {
            margin-right: 2px;
            width: 8px;
            display: inline-block;
            margin-top: 3px;
            height: 12px;
          }

          .age {
            display: inline-block;
            vertical-align: top;
            font-size: 12px;
            margin-top: 3px;
            line-height: 12px;
            height: 12px;
          }
        }

        .vip {
          width: 30px;
          margin-right: 7px;

          height: 16px;
          background: linear-gradient(180deg, #e8b87a 0%, #fde0b9 100%);
          border-radius: 8px;
          text-align: center;
          line-height: 17px;
          vertical-align: top;
          font-size: 12px;
          color: #663409;
        }
      }

      &>div:nth-child(2) {}
    }
  }
}

.center-class {
  align-items: flex-end !important;
}

.dibusrk-class {
  position: fixed;
  display: flex;
  width: 100%;
  // height: 50px;
  background: #ffffff;
  padding: 8px;
  box-sizing: border-box;
  align-items: center;
  bottom: 0px;

  &>div:nth-child(1) {
    margin-left: 16px;

    &>img {
      width: 24px;
      height: 24px;
    }
  }

  &>div:nth-child(2) {
    margin-left: 16px;

    &>img {
      width: 24px;
      height: 24px;
    }
  }

  &>div:nth-child(3) {
    margin-left: 16px;
    flex: 1;
    // height: 37px !important;

    ::v-deep & .van-cell {
      background: #f5f5f5;
      border-radius: 8px;
      padding: 7px 15px;
      height: 100%;
    }
  }

  &>div:nth-child(4) {
    margin-left: 8px;
    width: 64px;

    ::v-deep & .van-button__text {
      font-size: 14px !important;
      font-family: PingFangSC, PingFang SC !important;
      font-weight: 500 !important;
      color: #ffffff !important;
    }

    ::v-deep & .van-button {
      height: 35px !important;
      border-radius: 8px !important;
    }
  }
}

.msg-zlist-class {
  display: flex;
  align-items: center;
  padding: 8px;

  &>div:nth-child(1) {
    &>img {
      width: 48px;
      height: 48px;
      border-radius: 50%;
    }
  }

  &>div:nth-child(2) {
    margin-left: 8px;
    background: #f5f5f5;
    border-radius: 0px 4px 4px 4px;
    padding: 8px 7px;
    line-height: 15px;
    box-sizing: border-box;
  }
}

.msg-rlist-class {
  display: flex;
  align-items: center;
  padding: 8px;
  justify-content: flex-end;

  &>div:nth-child(2) {
    &>img {
      width: 48px;
      height: 48px;
      border-radius: 50%;
    }
  }

  &>div:nth-child(1) {
    margin-right: 8px;
    background: #f5f5f5;
    border-radius: 0px 4px 4px 4px;
    padding: 8px 7px;
    line-height: 15px;
    box-sizing: border-box;
  }
}
</style>
